import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import type { 
  Conversation, 
  ConversationsState, 
  ConversationListResponse,
  CreateConversationInput,
  Message 
} from '@/types'
import { messageService } from '@/services/message'

export const useConversationsStore = defineStore('conversations', () => {
  // State
  const conversations = ref<Conversation[]>([])
  const currentConversationId = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const conversationsList = computed(() => {
    return conversations.value.sort((a, b) => 
      new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    )
  })

  const currentConversation = computed(() => {
    if (!currentConversationId.value) return null
    return conversations.value.find(conv => conv.id === currentConversationId.value) || null
  })

  const totalUnreadCount = computed(() => {
    return conversations.value.reduce((total, conv) => total + conv.unreadCount, 0)
  })

  const getConversationById = computed(() => {
    return (conversationId: string): Conversation | undefined => {
      return conversations.value.find(conv => conv.id === conversationId)
    }
  })

  const getConversationByParticipants = computed(() => {
    return (participantIds: number[]): Conversation | undefined => {
      return conversations.value.find(conv => {
        if (conv.type === 'PRIVATE' && participantIds.length === 2) {
          return participantIds.every(id => conv.participants.includes(id))
        }
        return false
      })
    }
  })

  const activeConversations = computed(() => {
    return conversations.value.filter(conv => conv.isActive)
  })

  const mutedConversations = computed(() => {
    return conversations.value.filter(conv => conv.isMuted)
  })

  // Actions
  const loadConversations = async (): Promise<void> => {
    try {
      isLoading.value = true
      error.value = null

      const response = await messageService.getConversations()
      conversations.value = response.conversations || []
    } catch (err: any) {
      error.value = err.message || '加载会话列表失败'
    } finally {
      isLoading.value = false
    }
  }

  const createConversation = async (input: CreateConversationInput): Promise<Conversation | null> => {
    try {
      isLoading.value = true
      error.value = null

      // Note: This API doesn't exist yet, we'll need to implement it
      // For now, create a mock conversation
      const newConversation: Conversation = {
        id: `temp_${Date.now()}`,
        type: input.type,
        participants: input.participants,
        unreadCount: 0,
        title: input.title,
        avatar: input.avatar,
        updatedAt: new Date(),
        createdAt: new Date(),
        isActive: input.isActive,
        isMuted: input.isMuted
      }
      
      // Add to local state
      conversations.value.unshift(newConversation)
      return newConversation
    } catch (err: any) {
      error.value = err.message || '创建会话时发生错误'
      return null
    } finally {
      isLoading.value = false
    }
  }

  const setCurrentConversation = (conversationId: string | null): void => {
    currentConversationId.value = conversationId
    
    // Mark conversation as active when selected
    if (conversationId) {
      const conversation = conversations.value.find(conv => conv.id === conversationId)
      if (conversation && !conversation.isActive) {
        conversation.isActive = true
      }
    }
  }

  const updateConversation = (conversationId: string, updates: Partial<Conversation>): void => {
    const conversationIndex = conversations.value.findIndex(conv => conv.id === conversationId)
    
    if (conversationIndex !== -1) {
      conversations.value[conversationIndex] = {
        ...conversations.value[conversationIndex],
        ...updates,
        updatedAt: new Date()
      }
    }
  }

  const updateLastMessage = (conversationId: string, message: Message): void => {
    const conversation = conversations.value.find(conv => conv.id === conversationId)
    
    if (conversation) {
      conversation.lastMessage = message
      conversation.updatedAt = message.createdAt
      
      // Increment unread count if message is not from current user and conversation is not current
      if (conversationId !== currentConversationId.value && !message.isRead) {
        conversation.unreadCount += 1
      }
    }
  }

  const markConversationAsRead = async (conversationId: string): Promise<void> => {
    try {
      await messageService.markConversationAsRead(conversationId)
      
      // Update local state
      const conversation = conversations.value.find(conv => conv.id === conversationId)
      if (conversation) {
        conversation.unreadCount = 0
      }
    } catch (err: any) {
      console.error('Mark conversation as read failed:', err)
    }
  }

  const muteConversation = async (conversationId: string, mute: boolean = true): Promise<boolean> => {
    try {
      // Note: This API doesn't exist yet, we'll need to implement it
      // For now, just update the local state
      const conversation = conversations.value.find(conv => conv.id === conversationId)
      if (conversation) {
        conversation.isMuted = mute
        return true
      }
      return false
    } catch (err: any) {
      error.value = err.message || (mute ? '静音会话时发生错误' : '取消静音时发生错误')
      return false
    }
  }

  const deleteConversation = async (conversationId: string): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null

      // Note: This API doesn't exist yet, we'll need to implement it
      // For now, just remove from local state
      conversations.value = conversations.value.filter(conv => conv.id !== conversationId)
      
      // Clear current conversation if it was deleted
      if (currentConversationId.value === conversationId) {
        currentConversationId.value = null
      }
      
      return true
    } catch (err: any) {
      error.value = err.message || '删除会话时发生错误'
      return false
    } finally {
      isLoading.value = false
    }
  }

  const addConversation = (conversation: Conversation): void => {
    // Check if conversation already exists
    const existingIndex = conversations.value.findIndex(conv => conv.id === conversation.id)
    
    if (existingIndex === -1) {
      // Add new conversation
      conversations.value.unshift(conversation)
    } else {
      // Update existing conversation
      conversations.value[existingIndex] = conversation
    }
  }

  const removeConversation = (conversationId: string): void => {
    conversations.value = conversations.value.filter(conv => conv.id !== conversationId)
    
    if (currentConversationId.value === conversationId) {
      currentConversationId.value = null
    }
  }

  const clearUnreadCount = (conversationId: string): void => {
    const conversation = conversations.value.find(conv => conv.id === conversationId)
    if (conversation) {
      conversation.unreadCount = 0
    }
  }

  const incrementUnreadCount = (conversationId: string): void => {
    const conversation = conversations.value.find(conv => conv.id === conversationId)
    if (conversation && conversationId !== currentConversationId.value) {
      conversation.unreadCount += 1
    }
  }

  const clearError = (): void => {
    error.value = null
  }

  const refreshConversations = async (): Promise<void> => {
    await loadConversations()
  }

  // Find or create private conversation
  const findOrCreatePrivateConversation = async (participantId: number): Promise<Conversation | null> => {
    // First check if conversation already exists
    const existing = getConversationByParticipants.value([participantId])
    if (existing) {
      return existing
    }

    // Create new private conversation
    const input: CreateConversationInput = {
      type: 'PRIVATE',
      participants: [participantId],
      title: '', // Will be set by backend based on participant
      avatar: '',
      isActive: true,
      isMuted: false
    }

    return await createConversation(input)
  }

  return {
    // State
    conversations: readonly(conversations),
    currentConversationId: readonly(currentConversationId),
    isLoading: readonly(isLoading),
    error: readonly(error),
    
    // Getters
    conversationsList,
    currentConversation,
    totalUnreadCount,
    getConversationById,
    getConversationByParticipants,
    activeConversations,
    mutedConversations,
    
    // Actions
    loadConversations,
    createConversation,
    setCurrentConversation,
    updateConversation,
    updateLastMessage,
    markConversationAsRead,
    muteConversation,
    deleteConversation,
    addConversation,
    removeConversation,
    clearUnreadCount,
    incrementUnreadCount,
    clearError,
    refreshConversations,
    findOrCreatePrivateConversation
  }
})